﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using UI.Lib;
using UI.Lib.Factory;
using System.Collections;
using Components;
using Com.Seezt.Skins;
using DevExpress.XtraPivotGrid;
using Controls;
using UI.CommonForm;

namespace UI.ParentForm
{
    public partial class BasePivot : BaseForm
    {
        public BasePivot(string module, string action)
        {
            InitializeComponent();
            DevExpress.XtraPivotGrid.Localization.PivotGridLocalizer.Active = new LocalizerCN();

            this.ModuleCode = module;
            this.Action = action;

            PageInit();
            InitPivotGrid();
        }

        public virtual void PageInit()
        {
        }

        private void InitPivotGrid()
        {
            this.pvgridMain.FieldsCustomization(this.scLine.Panel1);

            Hashtable where = new Hashtable();
            where["pagename"] = this.GetType().FullName;

            //加载布局信息
            DataTable[] tables = CommonHelper.Entity.GetTables("Sys5a10Manager$GetDataSource", StringUtil.Entity.TableToJson(where));
            if (null == tables)
            {
                MsgBox.ShowErrorMsg(this, "数据源加载失败！");
            }
            else
            {
                if (tables[0] != null)//搜索框布局信息
                {
                    tbSummary.DataSource = tables[0];
                    tbSummary.AutoHeight = true;
                    tbSummary.DefaultWidth = Math.Max(tbSummary.DefaultWidth, 100);
                    tbSummary.RowHight = 30;
                    tbSummary.ColSize = 4;
                    tbSummary.Bind();
                }

                //绑定方案下拉框
                if (tables[1] != null)
                {
                    this.cbxSelutions.DataSource = tables[1];
                    this.cbxSelutions.DisplayMember = "providname";
                    this.cbxSelutions.ValueMember = "listid";
                }

                //绑定透视表
                if (tables.Length > 2 && null != tables[2])
                {
                    DataTable layout = tables[2];

                    LoadPivotGrid(layout);
                }
            }
        }

        private void LoadPivotGrid(DataTable layout)
        {
            PivotGridField pivotGridField = null;
            string formatstr = string.Empty;

            foreach (DataRow dr in layout.Rows)
            {
                pivotGridField = new PivotGridField(dr["columname"].ToString(), (PivotArea)Validation.ToInt(dr["ppt1"]));
                pivotGridField.SummaryType = (DevExpress.Data.PivotGrid.PivotSummaryType)Validation.ToInt(dr["tp9"]);
                pivotGridField.Caption = Validation.ToString(dr["headcn"]);
                pivotGridField.FieldName = dr["columname"].ToString();
                pivotGridField.Width = Validation.ToInt(dr["columnwidth"]);
                pivotGridField.Visible = ("n" == Validation.ToString(Global.IfNull(dr["ppt2"], dr["isshow"])).ToLower());
             
                formatstr = Validation.ToString(dr["tp7"]); //格式化字符串

                if (!string.IsNullOrEmpty(formatstr))
                {
                    string[] items = formatstr.Split(',');
                    if (items.Length != 0)
                    {
                        pivotGridField.CellFormat.FormatType = (DevExpress.Utils.FormatType)Validation.ToInt(items[0]);
                        if (items.Length > 1) pivotGridField.CellFormat.FormatString = items[1];
                    }
                }

                this.pvgridMain.Fields.Add(pivotGridField);
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            this.tbSummary.SetControlState(this.Action);
            _SetFontSize();
            ResetSize();
            this.tbSummary.FormatStyle();
        }

        void _SetFontSize()
        {
            this.Font = expSearchBox.Font = this.tbSummary.Font = Global.AllFont;
        }

        /// <summary>
        /// 根据概要的高度，重置明细的高度
        /// </summary>
        protected virtual void ResetSize()
        {
            int width = this.ClientSize.Width - 5;
            this.expSearchBox.Location = new Point(0, 0);
            this.expSearchBox.Size = new Size(width, this.expSearchBox.Height);

            this.tbSummary.Location = new Point(0, 26);
            this.tbSummary.Size = new Size(this.expSearchBox.Size.Width, this.expSearchBox.Size.Height);

            this.panToolBar.Location = new Point(this.expSearchBox.Location.X, this.expSearchBox.Location.Y + this.expSearchBox.Height);
            this.panToolBar.Size = new Size(width, this.panToolBar.Height);
            cbxSelutions.Height = panToolBar.Height;

            int winHeight = this.Height;
            this.panDetail.Location = new Point(this.panToolBar.Location.X, panToolBar.Height + panToolBar.Location.Y);
            this.panDetail.Size = new Size(width, winHeight - expSearchBox.Height - panToolBar.Height - 60);
        }

        private void expSearchBox_ExpandedChanged(object sender, DevComponents.DotNetBar.ExpandedChangeEventArgs e)
        {
            ResetSize();
        }

        /// <summary>
        /// 创建完控件后执行（添加属性）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void tbSummary_AfterCreateControl(object sender, Controls.Args.SummaryArgs e)
        {
            Control c = sender as Control;
            if (c == null) return;

            //添加默认事件
            AddEvent(c);

            //调用系统的创建控件
            AfterSummaryCreateControl(c.Name, c, e);
        }

        protected virtual void AfterSummaryCreateControl(string colName, Control c, Controls.Args.SummaryArgs e) { }

        protected override void AfterSummaryPopUp(PsPopWin popTarget, Hashtable hs, bool clearFlag, string status)
        {
            if (null == hs || 0 == hs.Count) return;

            Table targetTable = popTarget.Parent as Table;
            Control c = null;
            PsPopWin pop = null;
            string key = "";
            string value = "";
            bool isAlert = false;
            foreach (DictionaryEntry entry in hs)
            {
                key = entry.Key.ToString();
                value = (null == entry.Value || clearFlag) ? "" : entry.Value.ToString();
                if (key == "$SELF$")
                {
                    popTarget.Text = popTarget.Value = value;
                    if (!string.IsNullOrEmpty(value))
                    {
                        popTarget.PressWord = null;
                    }
                    if (!clearFlag && string.IsNullOrEmpty(value))
                    {
                        isAlert = true; //给出提示
                    }
                }
                else if (key.IndexOf("$VALUE$") > -1)//准备将值写入弹出框份额Value内
                {
                    if (key.IndexOf("&") > -1)//准备将值写入其他弹出框份额Value内
                    {
                        string name = key.Replace("$VALUE$&", "");
                        if (!targetTable.Controls.ContainsKey(name)) continue;

                        pop = targetTable.Controls[name] as PsPopWin;
                        if (pop == c) continue;

                        pop.Value = value;
                    }
                    else
                    {
                        popTarget.Value = value;
                    }
                }
                else
                {
                    targetTable.SetValue(key, value);
                }
            }

            if (isAlert && "M" != status)
            {
                popwin_MouseDoubleClick(popTarget, null);
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            DoSearch();
        }

        protected virtual void DoSearch() { }

        protected void BindGrid(DataTable dt)
        {
            this.pvgridMain.DataSource = dt;
        }

        private void btnSaveSelution_Click(object sender, EventArgs e)
        {
            if (this.cbxSelutions.Text.IndexOf(":") == -1 && !Context.IsSuperUser)
            {
                if (MsgBox.Show(this, "提示", "当前方案为公共样式，您没有权限修改，是否另存为？", MessageBoxButtons.YesNo)
                    == DialogResult.Yes)
                {
                    btnLSave.RaiseClick();
                }

                return;
            }

            SaveSln(this.cbxSelutions.SelectedValue.ToString(), false, "A");
        }

        private void SaveSln(string slnName, bool isPlublic, string type)
        {
            Hashtable table = new Hashtable();
            table["name"] = slnName;
            table["public"] = isPlublic ? "Y" : "N";
            table["page"] = this.GetType().FullName;

            //保存列信息
            DataTable dt = null;

            if (type != "D")
            {
                dt = new DataTable();
                dt.TableName = "DTLDATA";
                DataColumn dc;

                dc = new DataColumn();
                dc.ColumnName = "name";
                dt.Columns.Add(dc);

                dc = new DataColumn();
                dc.ColumnName = "area";
                dt.Columns.Add(dc);

                dc = new DataColumn();
                dc.ColumnName = "show";
                dt.Columns.Add(dc);

                PivotGridField field = null;
                for (int j = 0; j < this.pvgridMain.Fields.Count; j++)
                {
                    DataRow dr = dt.NewRow();
                    field = this.pvgridMain.Fields[j];

                    dr["name"] = field.FieldName;
                    dr["area"] = Convert.ToInt32(field.Area);
                    dr["show"] = field.Visible ? "N" : "Y"; //将错就错

                    dt.Rows.Add(dr);
                }
            }

            string errmsg = CommonHelper.Entity.SaveDtl("Sys5a10Manager$SaveSln",
                StringUtil.Entity.TableToJson(table), type, dt, null); //调用服务器的保存方法

            if (!string.IsNullOrEmpty(errmsg))
            {
                MsgBox.ShowErrorMsg(this, errmsg);
            }
            else
            {
                MsgBox.Show(this, "操作成功，下次打开此窗口时生效！");
            }
        }

        private void btnLSave_Click(object sender, EventArgs e)
        {
            FrmSaveStn frm = new FrmSaveStn();
            frm.PageName = this.GetType().FullName;
            frm.ShowDialog();

            if (!frm.Result) return;

            SaveSln(frm.GetSntName, frm.GetChkValue, "S");
        }

        private void cbxSelutions_SelectedIndexChanged(object sender, EventArgs e)
        {
            //选项值改变时加载布局方案

            this.pvgridMain.DataSource = null;
            this.pvgridMain.Fields.Clear();

            DataTable layout = CommonHelper.Entity.ExecFun("GetPivotLayout",
                    new KeyValuePair<string, object>("listid", this.cbxSelutions.SelectedValue));

            LoadPivotGrid(layout);
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (this.cbxSelutions.Text.IndexOf(":") == -1 && !Context.IsSuperUser)
            {
                MsgBox.Show(this, "公共的样式您没有权限删除！");

                return;
            }

            SaveSln(this.cbxSelutions.SelectedValue.ToString(), false, "D");
        }

        private void btnExportXls_Click(object sender, EventArgs e)
        {
            saveFileDialog1.Filter = "Excel格式(*.xls)|*.xls";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                this.pvgridMain.ExportToXls(saveFileDialog1.FileName);
            }
        }

        private void btnExportPdf_Click(object sender, EventArgs e)
        {
            saveFileDialog1.Filter = "PDF格式(*.pdf)|*.pdf";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                this.pvgridMain.ExportToPdf(saveFileDialog1.FileName);
            }
        }
    }
}
